<template>
  <q-chip v-for="item in sortList" :key="item.field" :icon-right="sortIcon(item.sort)" :ripple="false"
          :text-color="item.sort ? 'primary' : ''" class="cursor-pointer bg-transparent m-sorts-cls text-caption"
          clickable dense square @click.stop="handleSort(item)">
    {{ item.label }}
  </q-chip>
</template>

<script setup>
import { computed, ref, watch } from 'vue'

const props = defineProps({
  modelValue: Object,
  sorts: { type: Array, default: () => [] }
})
const emits = defineEmits(['refresh', 'update:modelValue'])

const sortList = ref([])
const setModelValue = () => emits('update:modelValue', sortList.value.filter(el => el.sort))

watch(() => props.sorts, val => {
  sortList.value = [...val]
  setModelValue()
}, { immediate: true })
const sortIcon = computed(() => sort => {
  if (!sort) return ''
  return sort === 'asc' ? 'mdi-arrow-up' : 'mdi-arrow-down'
})
const handleSort = e => {
  if (e.sort === 'asc') e.sort = 'desc'
  else if (e.sort === 'desc') e.sort = ''
  else e.sort = 'asc'
  setModelValue()
  emits('refresh')
}
</script>